﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using MadLibrary.Managing;

namespace MadLibrary.Net.Client
{
    /// <summary>
    /// Pararelly manages multiply communicators.
    /// </summary>
    public class CommunicationManager
    {
        /// <summary>
        /// Gets or sets collection of communicators which has to be managed.
        /// </summary>
        public Communicators Communicators { get; set; }

        /// <summary>
        /// Creates new empty communication manager.
        /// </summary>
        public CommunicationManager()
        {
            this.Communicators = new Communicators();
        }

        /// <summary>
        /// Creates new communication manager with specified communicators.
        /// </summary>
        /// <param name="Communicators">Specifies communicators whith have to be managed.</param>
        public CommunicationManager(params Communicator[] Communicators)
        {
            this.Communicators = new Communicators(Communicators);
        }

        /// <summary>
        /// Creates new communication manager with specified collection of communicators.
        /// </summary>
        /// <param name="Communicators">Specifies collection of communicators which has to be managed.</param>
        public CommunicationManager(Communicators Communicators)
        {
            this.Communicators = Communicators;
        }

        /// <summary>
        /// Opens connections of all communicators.
        /// </summary>
        public void OpenAll()
        {
            int i = 0;
            foreach (Communicator c in this.Communicators)
            {
                c.Open();
                i++;
            }
        }

        /// <summary>
        /// Requests all requests and receives all responses.
        /// </summary>
        public void RequestAll()
        {
            int i = 0;
            foreach (Communicator c in this.Communicators)
            {
                new Thread(new ThreadStart(() => { c.Request(); })).Start();
                i++;
            }
        }

        /// <summary>
        /// Disconnects all communicators.
        /// </summary>
        public void CloseAll()
        {
            int i = 0;
            foreach (Communicator c in this.Communicators)
            {
                c.Close();
                i++;
            }
        }

        /// <summary>Finalizes an instance of the CommunicationManager class.</summary>
        ~CommunicationManager()
        {
            this.CloseAll();
        }
    }
}